package com.situ.hibernate.test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.situ.hibernate.entity.Department;
import com.situ.hibernate.entity.User;
import com.situ.hibernate.util.HibernateUtil;

public class One2Many {

	//创建User和Department，将这些User加入指定Department，保存到数据库中，
	@Test
	public void test1() {
		Session session = HibernateUtil.openSession();
		Department department = new Department();
		department.setName("实施部");
		User user1 = new User("李1", 23, "123");
		User user2 = new User("李2", 23, "123");
		//表达关系：将这些User加入这个部门
		//表达一对多关系：一个部门有多个用户
		department.getUsers().add(user1);
		department.getUsers().add(user2);
		//表达多对一关系：多个用户属于一个部门
		user1.setDepartment(department);
		user2.setDepartment(department);
		
		session.save(department);
		session.save(user1);
		session.save(user2);
		session.close();
	}
	
	//为某个已经存在的部门添加一个新的用户
	@Test
	public void test2() {
		Session session = HibernateUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Department department = session.get(Department.class, 5);	
		User user = session.get(User.class, 1);
		department.getUsers().add(user);
		//user.setDepartment(department);
		//department和user都是持久化状态，所以update可以不写
		transaction.commit();
		session.close();
	}
	
	@Test
	public void test3() {
		Session session = HibernateUtil.openSession();
		Transaction trransaction = session.beginTransaction();
		Department department = session.get(Department.class, 5);
		User user = session.get(User.class, 1);
		department.getUsers().remove(user);
		trransaction.commit();
		session.close();
	}
	
	//创建User和Department，将这些User加入指定Department，保存到数据库中，
	@Test
	public void test111() {
		Session session = HibernateUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Department department = new Department();
		department.setName("运维部666");
		User user1 = new User("高7777", 23, "123");
		User user2 = new User("高8888", 23, "123");
		//表达关系：将这些User加入这个部门
		//表达一对多关系：一个部门有多个用户
		department.getUsers().add(user1);
		department.getUsers().add(user2);
		//表达多对一关系：多个用户属于一个部门
		//user1.setDepartment(department);
		//user2.setDepartment(department);
		
		session.save(department);
		//session.save(user1);
		//session.save(user2);
		transaction.commit();
		session.close();
	}
	
	@Test
	public void test33() {
		Session session = HibernateUtil.openSession();
		Transaction transaction = session.beginTransaction();
		Department department = session.get(Department.class, 10);
		session.delete(department);
		transaction.commit();
		session.close();
	}
}
